package com.wy.controller.wy;

import com.wy.bean.BuildingBean;
import com.wy.model.sys.Buildings;
import com.wy.model.sys.PageResult;
import com.wy.model.sys.UserEntity;
import com.wy.service.sys.UserService;
import com.wy.service.wy.BuildingService;
import com.wy.utils.BaseResponseInfo;
import com.wy.utils.ConstantData;
import com.wy.utils.FileUtil;
import com.wy.utils.HTTPStatus;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.ss.usermodel.Workbook;
import org.jeecgframework.poi.excel.ExcelExportUtil;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * 楼栋管理
 */

@RestController
@RequestMapping("/buildings")
@Api(value="API - BuildingController",tags={"楼栋管理"})
public class BuildingController {

	private Logger log = LoggerFactory.getLogger(BuildingController.class);

	@Resource(name = "buildingServiceImpl")
	private BuildingService buildingService;

	@Resource(name = "userServiceImpl")
	private UserService userService;

	/**
	 * 获取楼栋列表数据
	 * 
	 * @param pageSize
	 * @param page
	 * @param residenceId 小区id
	 * @param buildingName 楼栋名称
	 * @return
	 */
	@GetMapping("")
	@ApiOperation(value="BuildingList",notes="")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "pageSize", value = "每页显示条数", required = false,dataType = "Int", paramType = "query", defaultValue = "10"),
			@ApiImplicitParam(name = "page", value = "当前页数", required = false,dataType = "Int", paramType = "query",defaultValue = "1"),
			@ApiImplicitParam(name = "residenceId", value = "小区名称", required = false,dataType = "Int", paramType = "query",defaultValue = ""),
			@ApiImplicitParam(name = "buildingName", value = "楼栋名称", required = false,dataType = "String", paramType = "query",defaultValue = ""),
	})
	public PageResult buildingList(Integer pageSize, Integer page,Integer residenceId,String buildingName,
								   HttpServletRequest request) {
		List<String> rids = new ArrayList<>();
		UserEntity userEntity = userService.getUserByLoginName(request.getUserPrincipal().getName());
		if(null != userEntity) {
			String rid = userEntity.getRid();
			if(!StringUtils.isEmpty(rid)){
				List list = Arrays.asList(rid.split(","));
				rids = new ArrayList(list);
			}
		}

		PageResult pageResult = new PageResult();
		if("admin".equals(userEntity.getLoginName())) {
			rids = null;
		}else{
			rids.add("-1");//手动添加-1，如果当前登录用户无权限，则区别于admin的用户，查不到数据
		}

		pageResult.setData(buildingService.buildingList(pageSize, page * pageSize, residenceId, buildingName,rids));
		pageResult.setTotalCount(buildingService.buildingSize(pageSize, page * pageSize, residenceId, buildingName,rids));
		log.debug("The method is ending");
		return pageResult;
	}

	/**
	 * 新建楼栋信息
	 * @param buildings
	 * @return
	 */
	@PostMapping("/building")
	public Buildings insertBuilding(@RequestBody Buildings buildings) {
		buildingService.insertBuilding(buildings);
		log.debug("The method is ending");
		return buildings;
	}

	/**
	 * 修改楼栋信息
	 * @param buildings
	 * @param id
	 * @return
	 */
	@PutMapping("/{id}")
	public Buildings updateMenu(@RequestBody Buildings buildings, @PathVariable int id) {
		if (buildings.getId() == id) {
			buildingService.updateBuilding(buildings);
		}
		log.debug("The method is ending");
		return buildings;
	}

	/**
	 * 删除楼栋信息
	 * 
	 * @param groupId
	 * @return
	 */
	@DeleteMapping("/del")
	public void  deleteMenus(@RequestBody List<String> groupId) {
		buildingService.deleteBuilding(groupId);
	}

	/**
	 * 添加楼栋信息（无登录验证）
	 * @param buildings
	 * @return
	 */
	@ResponseBody
	@PostMapping("/save_building")
	public BaseResponseInfo saveHouse(@RequestBody Buildings buildings) {
		BaseResponseInfo baseResponseInfo = new BaseResponseInfo();
		Map<String, Object> data = new HashMap<String, Object>();
		try {
			buildingService.insertBuilding(buildings);
			baseResponseInfo.code = HTTPStatus.OK;
			data.put("message", ConstantData.MSG_SUCCESS_INFO);
		} catch (Exception ex){
			ex.printStackTrace();
			baseResponseInfo.code = HTTPStatus.INTERNAL_SERVER_ERROR;
		}
		baseResponseInfo.data = data;
		return baseResponseInfo;
	}

	/**
	 * 查询楼栋信息（无验证）
	 * @param pageSize
	 * @param start
	 * @return
	 */
//	@ResponseBody
//	@GetMapping("/get_building_list")
//	public BaseResponseInfo getBuildingList(@RequestParam("pageSize") int pageSize, @RequestParam("start")int start) {
//		BaseResponseInfo baseResponseInfo = new BaseResponseInfo();
//		Map<String, Object> data = new HashMap<String, Object>();
//		try {
//			data.put("houses", buildingService.buildingList(pageSize, (start -1)* pageSize,0,null,null));
//			data.put("count", buildingService.buildingSize(pageSize, (start -1) * pageSize,0,null,null));
//			baseResponseInfo.code = HTTPStatus.OK;
//			data.put("message", ConstantData.MSG_SUCCESS_INFO);
//		}catch(Exception ex){
//			ex.printStackTrace();
//			baseResponseInfo.code = HTTPStatus.INTERNAL_SERVER_ERROR;
//		}
//		baseResponseInfo.data = data;
//		return baseResponseInfo;
//	}


	/**
	 * 获取楼栋列表组成键值对数据（无验证）
	 * @param residenceId 小区id
	 * @return
	 */
	@GetMapping("/buildingByRid")
	public BaseResponseInfo getBuildingByResidenceId(Integer residenceId) {
		BaseResponseInfo baseResponseInfo = new BaseResponseInfo();
		baseResponseInfo.data = buildingService.getBuildingByResidenceId(residenceId);
		log.debug("The method is ending");
		return baseResponseInfo;
	}

	@GetMapping("/download")
	public void download(HttpServletRequest request, HttpServletResponse response,Integer residenceId,String buildingName,String username) throws Exception {
		// 告诉浏览器用什么软件可以打开此文件
		response.setHeader("content-Type", "application/vnd.ms-excel");
		// 下载文件的默认名称
		response.setHeader("Content-Disposition", "attachment;filename="+new String( "楼栋信息.xls".getBytes("gb2312"), "ISO8859-1" ));

		List<String> rids = new ArrayList<>();
		UserEntity userEntity = userService.getUserByLoginName(username);
		if(null != userEntity) {
			String rid = userEntity.getRid();
			if(!StringUtils.isEmpty(rid)){

				List list = Arrays.asList(rid.split(","));
				rids = new ArrayList(list);
			}
		}
		List<BuildingBean> list = new ArrayList<>();
		if("admin".equals(username)) {
			rids = null;
		} else {
			rids.add("-1");//手动添加-1，如果当前登录用户无权限，则区别于admin的用户，查不到数据
		}
		list = buildingService.buildingList(null,null, residenceId, buildingName,rids);
		Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams(), BuildingBean.class, list);
		workbook.write(response.getOutputStream());
	}

	/**
	 * 数据导入
	 * @param file
	 */
	@PostMapping("/import")
	public Map<String, String> importExcel(MultipartFile file){
		/*List<BuildingBean> buildingBeanList = FileUtil.importExcel(file,0,1,BuildingBean.class);
		System.out.println("导入数据一共【"+buildingBeanList.size()+"】行");
		if(buildingBeanList != null) {
			buildingService.insertBatch(buildingBeanList);
		}*/
		Map<String,String> map = FileUtil.judgeRepeatExcel(file,3,1);
		if(map.isEmpty()) {
			List<BuildingBean> buildingBeanList = FileUtil.importExcel(file,0,1,BuildingBean.class);
			if(buildingBeanList != null){
				List<BuildingBean> temp = buildingService.getBuildingListImport(buildingBeanList);
				if(temp.size() == 0){
					buildingService.insertBatch(buildingBeanList);
				}else{
					for(BuildingBean bb:temp){
						map.put(String.valueOf(bb.getId()),bb.getBuildingName());
					}
				}

			}
		}
		return  map;
	}

}
